const Router = require('koa-router');
const router = new Router();
const { apikeyList } = require('../utils/apikey')
const { getReply, getImage } = require('../utils/chatgpt');

// 聊天
router.get('/chat', async ctx => {
    try {
        const { code } = ctx.request.header;
        const { query } = ctx.query;
        // 验证code
        if (apikeyList.some(item => item.code === code)) {
            let apikey = apikeyList.find(item => item.code === code).apikey;
            if (query) {
                // 文字消息
                let messageList = [];
                messageList.push({
                    role: "user",
                    content: query
                })
                const res = await getReply(messageList,{ Authorization: `Bearer ${apikey}` });
                const message = res.data.choices[0].message.content;
                ctx.body = {
                    code: 200,
                    message: 'ok',
                    data: message
                }
            } else {
                ctx.body = {
                    code: 401,
                    message: '请输入问题描述'
                }
            }
        } else {
            ctx.body = {
                code: 405,
                message: '登陆码失效'
            }
        }
    } catch (error) {
        console.log(error)
        ctx.body = {
            code: 500,
            message: '服务器开小差了~',
            data: error
        }
    }
})

// 图片接口
router.get('/image', async ctx => {
    try {
        const { code } = ctx.request.header;
        const { query } = ctx.query;
        // 验证code
        if (apikeyList.some(item => item.code === code)) {
            let apikey = apikeyList.find(item => item.code === code).apikey;
            if (query) {
                const res = await getImage(query,{ Authorization: `Bearer ${apikey}` });
                const url = res.data.data[0].url;
                ctx.body = {
                    code: 200,
                    message: 'ok',
                    data: url
                }
            } else {
                ctx.body = {
                    code: 401,
                    message: '请输入图片描述'
                }
            }
        } else {
            ctx.body = {
                code: 405,
                message: '登陆码失效'
            }
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '服务器开小差了~',
            data: error
        }
    }
})

module.exports = router